package com.joven.core.utils;

import com.joven.core.constant.ResultInfo;
import com.joven.core.constant.Status;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @author joven_wong
 * 2021/6/24 17:14
 * 自定义全局异常处理类
 * 注解@RestControllerAdvice 代替@ControllerAdvice+@ResponseBody
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    //处理自定义异常
    @ExceptionHandler(value = BizException.class)
    public ResultInfo bizExceptionHandler(HttpServletRequest req, BizException e){
        log.error("发生业务异常！原因是：{}",e.getErrorMsg());
        return ResultInfo.fail(e.getErrorCode(), e.getErrorMsg());
    }

    //处理空指针异常
    @ExceptionHandler(value =NullPointerException.class)
    public ResultInfo exceptionHandler(HttpServletRequest req, NullPointerException e){
        log.error("发生空指针异常！原因是:",e);
        return ResultInfo.fail(Status.BODY_NOT_MATCH);
    }

    //处理其他异常
    @ExceptionHandler(value =Exception.class)
    public ResultInfo exceptionHandler(HttpServletRequest req, Exception e){
        log.error("发生系统异常！原因是:",e);
        return ResultInfo.fail(Status.SYSTEM_ERROR.getCode(), e.getMessage());
    }
}
